from flask import Flask, render_template, jsonify, request
import os
import appbuilder
from aip import AipImageClassify  # 假设使用百度AI图像识别API
from werkzeug.utils import secure_filename

app = Flask(__name__)

# 设置允许的文件上传目录
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 限制上传文件大小为16MB

# 设置环境TOKEN
os.environ["APPBUILDER_TOKEN"] = "bce-v3/ALTAK-X96iO5hyb2sN8KEhdiKoc/00e436f2edcb2733b26e19ef60f651c1aaa72fd3"
app_id = "94a09af2-a754-4ace-aca0-ba899fc477cb"
app_builder_client = appbuilder.AppBuilderClient(app_id)

# 初始化百度AI图像识别客户端
APP_ID = '115878780'  # 替换为你的百度AI App ID
API_KEY = '2ytPPKfWXLkk8xvRSK64mr0M'
SECRET_KEY = 'CmdxptQFZDFTAgs539H3vOFy4sV61I0m'
client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)


# 独立处理图片识别
@app.route('/analyze-image', methods=['POST'])
def analyze_image():
    try:
        # 获取用户上传的图片
        image_file = request.files['image']
        if image_file:
            # 保存图片到 'uploads' 文件夹中
            filename = secure_filename(image_file.filename)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            image_file.save(file_path)

            # 读取保存的图片文件
            with open(file_path, 'rb') as f:
                image = f.read()

            # 调用图像识别API，获取图像描述
            options = {"baike_num": 10}  # 返回至多5个百科信息
            image_result = client.advancedGeneral(image, options)

            # 提取图像描述
            if "result" in image_result and len(image_result['result']) > 0:
                image_description = image_result['result'][0]['keyword']  # 使用第一个识别结果的关键字
            else:
                image_description = "无法识别图片内容"

            # 返回图片识别结果
            return jsonify({"image_description": image_description})

        else:
            return jsonify({"error": "没有上传图片"}), 400

    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 独立处理问题查询
@app.route('/ask-question', methods=['POST'])
def ask_question():
    try:
        # 获取用户输入的问题
        user_query = request.json.get('query')

        # 调用AppBuilder API处理问题
        conversation_id = app_builder_client.create_conversation()
        resp = app_builder_client.run(conversation_id, user_query)

        # 返回AI的答案
        return jsonify({"answer": resp.content.answer})

    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 处理图像和问题结合的AI解析
@app.route('/process-image-and-query', methods=['POST'])
def process_image_and_query():
    try:
        # 获取用户上传的图片
        image_file = request.files['image']
        if image_file:
            # 保存图片到 'uploads' 文件夹中
            filename = secure_filename(image_file.filename)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            image_file.save(file_path)

            # 读取保存的图片文件
            with open(file_path, 'rb') as f:
                image = f.read()

            # 获取用户输入的问题
            user_query = request.form.get('query')

            # 调用图像识别API，获取图像描述
            options = {"baike_num": 10}  # 返回至多5个百科信息
            image_result = client.advancedGeneral(image, options)

            # 提取图像描述
            if "result" in image_result and len(image_result['result']) > 0:
                image_description = image_result['result'][0]['keyword']  # 使用第一个识别结果的关键字
            else:
                image_description = "无法识别图片内容"

            # 将图像描述和用户问题结合
            combined_query = f"图像描述: {image_description}. 用户的问题: {user_query}"

            # 调用AppBuilder API，将组合后的问题发送
            conversation_id = app_builder_client.create_conversation()
            resp = app_builder_client.run(conversation_id, combined_query)

            # 返回AI的答案
            return jsonify({"answer": resp.content.answer})

        else:
            return jsonify({"error": "没有上传图片"}), 400

    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 首页，展示HTML页面
@app.route('/')
def index():
    return render_template('index.html')


if __name__ == '__main__':
    app.run(debug=True, port=5500)
